package com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser;

import cn.hutool.core.util.StrUtil;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shengqiang.wu
 * @date 2019/12/24/024 10:50
 * @desc
 */
@Setter
@Accessors(chain = true)
@Slf4j
public class TenantWebInterceptor extends HandlerInterceptorAdapter {

    private String interceptType;

    private String interceptKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果interceptType 为空,默认为 header
        if(StrUtil.isEmpty(interceptType)){
            interceptType = "header";
        }
        //interceptKey 为空,默认为 tenantId
        if(StrUtil.isEmpty(interceptKey)){
            interceptKey = "tenantId";
        }

        String tenant = null;
        switch (interceptType){
            case "header":
                tenant = request.getHeader(interceptKey);
                break;
            case "parameter":
                tenant = request.getParameter(interceptKey);
                break;
        }

        if(StrUtil.isNotEmpty(tenant)){
            TenantContext.threadLocal.set(tenant);
        }

       return super.preHandle(request,response,handler);
    }
}
